package com.ruicar.afs.cloud.afscase.infomanagement.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.approvetask.entity.CaseApproveRecord;
import com.ruicar.afs.cloud.afscase.approvetask.service.CaseApproveRecordService;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelWitnessInfo;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelWitnessInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseChannelInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseContractInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCustInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseChannelInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseContractInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseCustInfoService;
import com.ruicar.afs.cloud.afscase.loanactivatepool.entity.LoanActivatePool;
import com.ruicar.afs.cloud.afscase.loanactivatepool.service.LoanActivateService;
import com.ruicar.afs.cloud.afscase.loanapprove.entity.LoanBankCardInfo;
import com.ruicar.afs.cloud.afscase.loanapprove.service.LoanBankCardInfoService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ContractStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.BankCardVo;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.BankListVo;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.LoanProgressVo;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.LoanScheduleVo;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.components.datadicsync.DicHelper;
import com.ruicar.afs.cloud.components.datadicsync.dto.DicDataDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: sang jian
 * @date: 2020/9/22 14:27
 * @description:
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api("客户银行卡信息")
@RequestMapping("/CaseBankInfo")
public class CaseBankInfoController {

    private final CaseCustInfoService caseCustInfoService;
    private final LoanBankCardInfoService loanBankCardInfoService;
    private final CaseContractInfoService caseContractInfoService;
    private final CaseBaseInfoService caseBaseInfoService;
    private final LoanActivateService loanActivateService;
    private final CaseApproveRecordService caseApproveRecordService;
    private final ChannelWitnessInfoService channelWitnessInfoService;
    private final ChannelBaseInfoService channelBaseInfoService;
    private final CaseChannelInfoService caseChannelInfoService;

    @PostMapping(value = "/getBankNumByCertNoOrApplyNo")
    @ApiOperation(value = "通过身份证号或申请号查询还款银行卡号")
    public IResponse<BankListVo> getBankNumByIdOrApplyNo(@RequestParam(value = "applyNo",required = false) String applyNo, @RequestParam(value = "certNo",required = false) String certNo) {
        if(StringUtils.isEmpty(applyNo) || StringUtils.isEmpty(certNo)){
            log.error("------------------通过身份证号或申请号查询还款银行卡号，入参为空------------------");
            return IResponse.fail("入参不能为空");
        }
        //01-主借人、02-共借人、03-担保人
        String mainRole = "01";
        //合同激活
        String activate = "activate";
        BankListVo bankListVo = new BankListVo();
        List<BankCardVo> bankCardVoList = new ArrayList<>();
        //获取主借人信息
        List<CaseCustInfo> custInfos = caseCustInfoService.list(Wrappers.<CaseCustInfo>query().lambda()
                .eq(CaseCustInfo::getCustRole, mainRole)
                .and(wrapper1 -> wrapper1.eq(StringUtils.isNotBlank(applyNo) && StringUtils.isBlank(certNo), CaseCustInfo::getApplyNo, applyNo)
                        .or(wrapper2 -> wrapper2.eq(StringUtils.isNotBlank(certNo), CaseCustInfo::getCertNo, certNo))));
        if (custInfos != null && custInfos.size() > 0) {
            //获取银行卡信息
            List<String> applyNos = new ArrayList<>();
            for (CaseCustInfo caseCustInfo : custInfos) {
                applyNos.add(caseCustInfo.getApplyNo());
            }
            log.info("------------------通过身份证号或申请号查询还款银行卡号，查询到的申请编号数据：{}------------------",applyNos);
            List<LoanBankCardInfo> bankCardInfoList = loanBankCardInfoService.list(Wrappers.<LoanBankCardInfo>query().lambda()
                    .in(LoanBankCardInfo::getApplyNo, applyNos));
            if (bankCardInfoList != null && bankCardInfoList.size() > 0) {
                for (LoanBankCardInfo info : bankCardInfoList) {
                    BankCardVo bankCardVo = new BankCardVo();
                    //翻译银行
                    BeanUtils.copyProperties(info, bankCardVo);
                    bankCardVo.setBankCode(dicData(info.getBankCode(),"bankCode"));
                    String status = "";
                    ContractStatusEnum contractStatus = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda()
                            .eq(CaseContractInfo::getContractNo, info.getContractNo())).getContractStatus();
                    switch (contractStatus){
                        case create: status = "0";break;
                        case approve: status = "0";break;
                        case swindleRefuse: status = "0";break;
                        case refuse: status = "0";break;
                        case flatCancel: status = "0";break;
                        case contractCancel: status = "0";break;
                        case contractEffective: status = "1";break;
                        case normalSettle: status = "1";break;
                        case advanceSettle: status = "1";break;
                        case writeOff: status = "1";break;
                        case close: status = "0";break;
                        default:status = "0";break;
                    }
                    bankCardVo.setCaseStatus(status);
                    bankCardVoList.add(bankCardVo);
                }
                log.info("------------------还款卡信息查询数量：{}------------------",bankCardInfoList.size());
            }

            bankListVo.setBankCards(bankCardVoList);
            //查合同数量
            List<CaseContractInfo> contractInfoList = caseContractInfoService.list(Wrappers.<CaseContractInfo>query().lambda()
                    .in(CaseContractInfo::getApplyNo, applyNos));
            if (contractInfoList.size() > 0) {
                bankListVo.setCount(contractInfoList.size());
            } else {
                bankListVo.setCount(1);
            }
        }else{
            log.info("------------------查询不到主借人信息,不返回数据------------------");
            return IResponse.fail("贷前未查询到任何数据");
        }
        return IResponse.fail("贷前未查询到任何数据");
    }



    @PostMapping(value = "/getAllContractsByCerNo")
    @ApiOperation(value = "通过身份证号获取所有合同")
    public IResponse<List<LoanProgressVo>> getAllContractsByCerNo(@RequestParam(value = "certNo") String certNo) {

        //01-主借人、02-共借人、03-担保人
        String mainRole = "01";
        //合同激活
        String activate = "activate";
        List<LoanProgressVo> vos = new ArrayList<>();
        //获取主借人信息
        List<CaseCustInfo> custInfos = caseCustInfoService.list(Wrappers.<CaseCustInfo>query().lambda()
                .eq(CaseCustInfo::getCustRole, mainRole)
                .eq(CaseCustInfo::getCertNo, certNo));

        if(CollectionUtils.isNotEmpty(custInfos)){
            for (CaseCustInfo caseCustInfo : custInfos) {
                //查合同
                List<CaseContractInfo> contractInfoList = caseContractInfoService.list(Wrappers.<CaseContractInfo>query().lambda()
                        .eq(CaseContractInfo::getApplyNo, caseCustInfo.getApplyNo()));

                if (contractInfoList.size() > 0) {
                    for (CaseContractInfo caseContractInfo : contractInfoList){
                        LoanActivatePool pool = loanActivateService.getOne(Wrappers.<LoanActivatePool>query().lambda()
                                .eq(LoanActivatePool::getContractNo, caseContractInfo.getContractNo()));
                        if(pool != null && activate.equals(pool.getActStatus())){
                            break;
                        }
                        LoanProgressVo loanProgressVo = new LoanProgressVo();
                        loanProgressVo.setCertNo(caseCustInfo.getCertNo());
                        loanProgressVo.setContractNo(caseContractInfo.getContractNo());
                        loanProgressVo.setCaseStatus("0");
                        loanProgressVo.setCreateDate(caseContractInfo.getStartDate());
                        loanProgressVo.setTelPhone(caseCustInfo.getTelPhone());
                        vos.add(loanProgressVo);
                    }
                } else {
                    LoanProgressVo loanProgressVo = new LoanProgressVo();
                    loanProgressVo.setCertNo(caseCustInfo.getCertNo());
                    loanProgressVo.setCaseStatus("0");
                    loanProgressVo.setContractNo(caseCustInfo.getApplyNo());
                    loanProgressVo.setCreateDate(null);
                    loanProgressVo.setTelPhone(caseCustInfo.getTelPhone());
                    vos.add(loanProgressVo);
                    log.info("------------------查不到合同信息,返回申请号------------------");
                }
            }
        }else{
            log.info("------------------通过身份证号查询不到主借人信息------------------");
        }
        return IResponse.success(vos);
    }


    @PostMapping(value = "/getLoanSchedule")
    @ApiOperation(value = "通过申请编号查询贷款进度")
    public IResponse<LoanScheduleVo> getLoanSchedule(@RequestParam(value = "applyNo",required = false) String applyNo) {
        log.info("------------------通过申请编号查询贷款进度入参为：[{}],------------------",applyNo);
        if(EmptyUtils.isEmpty(applyNo)||"null".equals(applyNo)){
            return IResponse.fail("申请编号入参不能为空");
        }
        //合同激活
        String activate = "activate";
        LoanScheduleVo loanScheduleVo = new LoanScheduleVo();
        //查询base表
        CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda().eq(CaseBaseInfo::getApplyNo, applyNo));
        if(caseBaseInfo == null){
            log.info("------------------查询base表,查询不到案件数据------------------");
            return IResponse.fail("查询不到案件数据");
        }
        loanScheduleVo.setIntoFirstDate(caseBaseInfo.getPassFirstDate());
        loanScheduleVo.setApproveStatus(caseBaseInfo.getBusinessStateIn());
        //查询合同表
        List<CaseContractInfo> caseContractInfos = caseContractInfoService.list(Wrappers.<CaseContractInfo>query().lambda()
                .eq(CaseContractInfo::getApplyNo, applyNo));
        if(CollectionUtils.isNotEmpty(caseContractInfos)){
            log.info("------------------查询合同关表数据------------------");
            CaseContractInfo caseContractInfo = caseContractInfos.get(0);
            LoanActivatePool pool = loanActivateService.getOne(Wrappers.<LoanActivatePool>query().lambda()
                    .eq(LoanActivatePool::getContractNo, caseContractInfo.getContractNo()));
            if(pool != null && activate.equals(pool.getActStatus())){
                log.info("------------------合同状态为已激活,不返回数据------------------");
                return IResponse.fail("合同状态为已激活,不返回数据");
            }
            String contractNo = caseContractInfo.getContractNo();
            //查询审批记录表
            List<CaseApproveRecord> recordList = caseApproveRecordService.list(Wrappers.<CaseApproveRecord>query().lambda()
                    .eq(CaseApproveRecord::getContractNo, contractNo)
                    .orderByDesc(CaseApproveRecord::getCreateTime));
            //最新的审批记录
            CaseApproveRecord caseApproveRecord = recordList.get(0);
            loanScheduleVo.setContractNo(contractNo);
            loanScheduleVo.setStartDate(caseApproveRecord.getCreateTime());
            loanScheduleVo.setApproveOperator(caseApproveRecord.getDisposeStaff());
            loanScheduleVo.setApproveDate(caseApproveRecord.getCreateTime());
            loanScheduleVo.setContractStatus(caseContractInfo.getApplyStatus());
            loanScheduleVo.setActiveOperator(caseApproveRecord.getCreateBy());
            loanScheduleVo.setActiveDate(caseContractInfo.getStartDate());
            return IResponse.success(loanScheduleVo);
        }else{
            log.info("------------------合同表未查询到数据,开始查询审批记录表------------------");
            //查询审批记录表
            List<CaseApproveRecord> recordList = caseApproveRecordService.list(Wrappers.<CaseApproveRecord>query().lambda()
                    .eq(CaseApproveRecord::getApplyNo, applyNo)
                    .orderByDesc(CaseApproveRecord::getCreateTime));
            CaseApproveRecord caseApproveRecord = recordList.get(0);
            loanScheduleVo.setContractNo(applyNo);
            loanScheduleVo.setStartDate(caseApproveRecord.getCreateTime());
            loanScheduleVo.setApproveOperator(caseApproveRecord.getDisposeStaff());
            loanScheduleVo.setApproveDate(caseApproveRecord.getCreateTime());
            loanScheduleVo.setContractStatus(caseBaseInfo.getBusinessStateIn());
            loanScheduleVo.setActiveDate(null);
            loanScheduleVo.setActiveOperator(caseApproveRecord.getCreateBy());
            log.info("------------------ActiveDate和ApproveOperator为空时,则是数据库该字段无数据------------------");
            return IResponse.success(loanScheduleVo);
        }
    }


    //字典翻译
    public static String dicData(String param,String dicType){
        String result = "";
        Map<String, List<DicDataDto>> listMap = DicHelper.getDicMaps(dicType);
        List<DicDataDto> list=listMap.get(dicType);
        for(DicDataDto dicDataDto:list){
            if(dicDataDto.getValue().equals(param)){
                result = dicDataDto.getTitle();
            }
        }
        return result;
    }

    /**
     * 根据合同号查询见证人姓名
     */
    @PostMapping(value = "/getWitnessInfo")
    @ApiOperation(value = "根据合同号查询见证人姓名")
    public IResponse<String> getWitnessInfo(@RequestParam(value = "contractNo",required = false) String contractNo) {
        log.info("------------------根据合同号查询见证人姓名入参为：[{}],------------------",contractNo);
        if(StringUtils.isEmpty(contractNo)){
            return IResponse.fail("合同号不允许为空");
        }

        CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda().eq(CaseContractInfo::getContractNo, contractNo));
        log.info("------------------caseContractInfo查询到的：[{}],------------------",contractNo);
        if(caseContractInfo == null){
            return IResponse.fail("未查询到操作人信息！");
        }

        CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda().eq(CaseChannelInfo::getApplyNo, caseContractInfo.getApplyNo()));
        if(caseChannelInfo==null){
            return IResponse.fail("未查询到操作人信息！");
        }
        ChannelBaseInfo channelBaseInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda().eq(ChannelBaseInfo::getChannelCode, caseChannelInfo.getDealerNo()));
        if(channelBaseInfo==null){
            return IResponse.fail("未查询到操作人信息！");
        }
        ChannelWitnessInfo channelWitnessInfo = channelWitnessInfoService.getOne(Wrappers.<ChannelWitnessInfo>query().lambda()
                .eq(ChannelWitnessInfo::getChannelId, channelBaseInfo.getChannelId())
                .eq(ChannelWitnessInfo::getWitnessIdCard, caseContractInfo.getWitnessId())
                .eq(ChannelWitnessInfo::getBusinessAttributes, caseContractInfo.getBusinessType()));
        if (channelWitnessInfo==null){
            return IResponse.fail("未查询到操作人信息！");
        }
        return IResponse.success(channelWitnessInfo.getWitnessName());
    }


}
